// 日志模块
const pino = require('pino');
const pinoPretty = require('pino-pretty');
const rotatingFile = require('file-stream-rotator');
const { writeToDatabase } = require('./dbHandler.js');

// 创建控制台输出源配置

const consoleStream = pinoPretty({
  colorize: true,
  translateTime: 'SYS:standard',
  ignore: 'req.headers',
  messageFormat: (log, messageKey) => {
    return log[messageKey];
  }
})

// 创建文件输出源配置

const rotatingLogStream  = rotatingFile.getStream({
  filename: './logs/log-%DATE%.log',
  frequency: 'daily',
  verbose: false,
  date_format: "YYYY-MM-DD",
  max_logs: '15d',
  audit_file: "./tmp/log-audit.json"
});

// 创建输出源数据库配置, writeToDatabase是一个模拟写入数据库的函数

const dbStream = {
  write: async ( log ) => {
    // 后续添加
    //  try {
    //     const result = await writeToDatabase(log)
    //  }
    //  catch(error) {
    //     console.log(error)
    //  }
  }
}

// 创建多输出源配置

const multiStream = pino.multistream([
  { level: 'trace', stream: consoleStream },
  { level: 'info', stream: rotatingLogStream },
  { level: 'info', stream: dbStream }
])

module.exports = multiStream;

